package com.py.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.py.common.constants.ScheduleConstants;
import com.py.common.redis.CacheService;
import com.py.model.common.dtos.ResponseResult;
import com.py.model.schedule.dtos.Task;
import com.py.model.schedule.pojos.Taskinfo;
import com.py.model.schedule.pojos.TaskinfoLogs;
import com.py.schedule.mapper.TaskinfoLogsMapper;
import com.py.schedule.mapper.TaskinfoMapper;
import com.py.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2022/11/14 10:28
 * @Version 1.0
 */
@Service
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Resource
    private TaskinfoMapper taskinfoMapper;

    @Resource
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 存入数据库或缓存
     *
     * @param task
     * @return
     */
    @Override
    public ResponseResult addTask(Task task) {

        //存入Db
        saveTask(task);

        //获取5分钟之后时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long afterTime = calendar.getTimeInMillis();

        //如果执行时间小于当前时间,写入数据到list
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            String key = ScheduleConstants.TOPIC + task.getTaskType() + "-" + task.getPriority();
            cacheService.lLeftPush(key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= afterTime) {
            //如果小于等于5分钟后,写入到zset
            String key = ScheduleConstants.FUTURE + task.getTaskType() + "-" + task.getPriority();
            cacheService.zAdd(key, JSON.toJSONString(task), task.getExecuteTime());
        }
        return ResponseResult.okResult(task.getTaskId());
    }

    /**
     * 分别存入info及infoLog表
     */
    public void saveTask(Task task) {
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        taskinfoMapper.insert(taskinfo);

        TaskinfoLogs logs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo, logs);
        logs.setVersion(1);
        logs.setStatus(ScheduleConstants.SCHEDULED);
        taskinfoLogsMapper.insert(logs);
    }


    /**
     * 拉取list缓存数据执行并删除taskinfo中保存的数据
     *
     * @param type 文章
     * @param prority
     * @return
     */
    @Override
    public Task poll(Integer type, Integer prority) {
        String key = ScheduleConstants.TOPIC + type + "-" + prority;
        //从list取出数据并删除数据
        String jsonString = cacheService.lRightPop(key);
        if (StringUtils.isEmpty(jsonString)) {
            log.info("list缓存中无数据");
            return null;
        }
        Task task = JSON.parseObject(jsonString, Task.class);

        //数据消费完成,删除数据库和改变状态
        updateDb(task,ScheduleConstants.EXECUTED);

        return task;
    }

    /**
     * 任务执行成功,删除任务和更新日志数据库
     *
     * @param task -任务
     *        status - 更新状态
     */
    private void updateDb(Task task,int status) {
        //删除任务信息表
        taskinfoMapper.deleteById(task.getTaskId());

        //更新任务日志表
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(task.getTaskId());
        //日志状态更新
        taskinfoLogs.setStatus(status);
        taskinfoLogsMapper.updateById(taskinfoLogs);
    }


    /**
     * 定时刷新zset的数据到list执行
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    @PostConstruct //初始化注解  一旦开启服务就立即执行一次
    public void pushExecTask() {
        log.info("开始执行zset到list任务");
        String flag = cacheService.tryLock("Task-pushExecTask", 30000);
        if (flag == null) {
            log.info("未获取到锁，不执行");
            return;
        }
        Set<String> fetures = cacheService.scan(ScheduleConstants.FUTURE + "*");
        if (CollectionUtils.isEmpty(fetures)) {
            log.info("没有需求执行的任务");
            return;
        }
        for (String fetureKey : fetures) {
            //获取当前时间数据的key
            String topicKey = ScheduleConstants.TOPIC + fetureKey.split(ScheduleConstants.FUTURE)[1];
            //查询<=当前时间的任务数据
            Set<String> taskList = cacheService.zRangeByScore(fetureKey, 0, System.currentTimeMillis());

            //利用redis管道技术将任务数据存入list中
            cacheService.refreshWithPipeline(fetureKey, topicKey, taskList);
            log.info("完成key:{}的数据到list刷新", fetureKey);
        }
    }

    /**
     * 定时刷新数据库的数据到zset缓存
     */
//    @PostConstruct //初始化注解  一旦开启服务就立即执行一次
    @Scheduled(cron = "0 0/5 * * * ?")
    public void loadDataToZset() {
        log.info("开始执行从数据库将最近5分钟需要执行的任务添加到zset中");
        String flag = cacheService.tryLock("Task-loadDataToZset", 3000);
        if (flag == null) {
            log.info("未获取到锁，不执行");
            return;
        }
        //清理缓存中的数据  防止缓存中未消费又加载同样数据库的数据 又将数据库的数据多次刷进zset缓存
        clearCache();

        //查询5分钟内的数据
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery()
                .lt(Taskinfo::getExecuteTime, calendar.getTime()));

        for (Taskinfo taskinfo : taskinfos) {
            String key = ScheduleConstants.FUTURE + taskinfo.getTaskType() + "-" + taskinfo.getPriority();
            Task task = new Task();
            BeanUtils.copyProperties(taskinfo, task);
            task.setExecuteTime(taskinfo.getExecuteTime().getTime());
            cacheService.zAdd(key, JSON.toJSONString(task), taskinfo.getExecuteTime().getTime());
            log.info("成功将数据刷新到zset");
        }
    }

    /**
     * 清理缓存中的数据
     */
    private void clearCache() {
        Set<String> topickeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futurekeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topickeys);
        cacheService.delete(futurekeys);
    }

}